import React, { useEffect, useState,useRef } from 'react'
import { Modal, Layout, Menu, Breadcrumb, Button, Cascader, Space, message, Table, Input, InputNumber, Popconfirm, Form, Typography } from 'antd';
import {  EditTwoTone, DeleteTwoTone, ExclamationCircleOutlined } from '@ant-design/icons';
import {screenWidth} from '../../../Constants'
import { useNavigate } from 'react-router-dom'
import axios from 'axios';
import provinceData  from '../../../js/provinceData';
import { isOwnEmpty } from '../../../js/isEmptyObjc';
const { confirm } = Modal;
const { Search } = Input;
const { Content, } = Layout;
export default function Index() {
  let editOrgInfo = {}
  const navigate = useNavigate()
  const [originData, setOriginData] = useState(0);
  const [orglist, setOrglist] = useState(0);
  const [editvisible, seteditVisible] = useState(false);
  const pwdRef = useRef();
  const nameRef = useRef();
  const addressRef = useRef();
  const phoneRef = useRef();
  const emailRef = useRef();
  const orgmsgRef = useRef();
  const [currentOrg, setCurrentOrg] = useState();
  useEffect(() => {
    message.destroy();
    axios.get("http://localhost:8080/qryOrgList").then(resp => {
      setOriginData(resp.data.data)
      setOrglist(resp.data.data)
      console.log(resp.data.data);
    })
    return () => {
      console.log('menu-destroy');
    };
  }, []);
  const deleteUser = (record) => {
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: `确认要删除${record.orgname}吗?`,
      onOk() {
        console.log(record);
        axios.post("http://localhost:8080/delOrg?orgid=" + record.id).then(resp => {
          if (resp.data.state === "0") {
            message.success(resp.data.message, 1);
            setTimeout(() => {
              window.location.reload()
            }, 500);
          } else {
            message.error(resp.data.message, 1)
          }

        }).catch(err => {
          console.log(err);
          message.error("网络超时!", 1)
        })
      },
    });
  }



  const columns = [
    {
      title: '机构名称',
      dataIndex: 'orgname',
      ellipsis: true,
    },
    {
      title: 'address',
      dataIndex: 'address',
      ellipsis: true,
    },
    {
      title: 'phone',
      dataIndex: 'phone',
      ellipsis: true,
    },
    {
      title: 'email',
      dataIndex: 'email',
      ellipsis: true,
    },
    {
      title: '积分',
      dataIndex: 'point',
      ellipsis: true,
      sorter: (a, b) => a.point - b.point,
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick = {() => {showModal(record)}}>编辑<EditTwoTone /></a>
          <a onClick={() => { deleteUser(record) }} style={{ marginLeft: 5 }}> 删除<DeleteTwoTone twoToneColor="red" /></a>
        </Space>
      ),
    },
  ];
  const renderTableHead = () => {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span>机构管理</span>
        <Search placeholder="搜索名称" onSearch={onSearch} allowClear style={{ width: 200 }} />
      </div>
    )
  }
  const onSearch = (value) => {
    console.log(value);
    let rs = [];
    rs = originData.filter((item, index) => {
      console.log(item);
      return item.orgname.indexOf(value) != -1
    })
    console.log(rs);
    setOriginData(rs)
    if (value == null || value == "") {
      setOriginData(orglist)
    }

  }
  const showModal = (record) => {
    seteditVisible(true);
    setCurrentOrg(record);
    pwdRef.current.state.value = '';
    nameRef.current.state.value = '';
    addressRef.current.state.value = '';
    phoneRef.current.state.value = '';
    emailRef.current.state.value = '';
  };

  const handleOk = () => {
    editOrgInfo.password = pwdRef.current.state.value || null;
    editOrgInfo.orgname = nameRef.current.state.value || null;
    editOrgInfo.address = addressRef.current.state.value || null;
    editOrgInfo.phone = phoneRef.current.state.value || null;
    editOrgInfo.email = emailRef.current.state.value || null;
    editOrgInfo.orgmsg = orgmsgRef.current.resizableTextArea.textArea.value || null
    console.log("修改后机构信息:", editOrgInfo);  
    if (isOwnEmpty(editOrgInfo)) {
      seteditVisible(false);
      return;
    }
    editOrgInfo.id = currentOrg.id;
    const emailreg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    const phonereg = /^1[3|4|5|7|8]\d{9}$/
    const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
    if (editOrgInfo.email != null) {
      if ( !emailreg.test(editOrgInfo.email)) {
        message.error("邮箱格式错误!")
        seteditVisible(false);
        return
      }
     
    }
    if (editOrgInfo.phone != null) {
      if (!phonereg.test(editOrgInfo.phone)) {
        message.error("手机格式错误!")
        seteditVisible(false);
        return
      }
    }
    if (editOrgInfo.password != null) {
      if (!pwdReg.test(editOrgInfo.phone)) {
        message.error("密码为6-18位数字字母组合!")
        seteditVisible(false);
        return
      }
    }
    axios.post("http://localhost:8080/editOrg", editOrgInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        seteditVisible(false);
        setTimeout(() => {
          window.location.reload();
        }, 500);

      } else {
        message.error(resp.data.message, 1)
      }

    }).catch(err => {
      message.error("请求超时!", 1);
      setTimeout(() => {
        navigate('/adminMenu/allOrg/*')
        seteditVisible(false);
      }, 1000);

    })

  };



  const citySelect = (value) => {
    let cityStr = ""
    for (const v of value) {
      cityStr += v;
    }

    console.log(cityStr);
    editOrgInfo.city = cityStr;
  }

  const handleCancel = () => {
    seteditVisible(false);
    editOrgInfo = {}
  };
  return (
    <Content style={{ minHeight: 285 }} className="animate__animated animate__fadeIn">
      <Table columns={columns}
      dataSource={originData}
      bordered
      title={renderTableHead}
      
    />
       <Modal
        title="编辑资料"
        visible={editvisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={'35%'}
        centered={true}
      >
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>密码</span><Input style={{ width: screenWidth * 0.2 }} ref={pwdRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>机构名称</span><Input style={{ width: screenWidth * 0.2 }} ref={nameRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>详细地址</span><Input style={{ width: screenWidth * 0.2 }} ref={addressRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>联系电话</span><Input style={{ width: screenWidth * 0.2 }} ref={phoneRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>电子邮箱</span><Input style={{ width: screenWidth * 0.2 }} ref={emailRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>城市</span><Cascader style={{ width: screenWidth * 0.2 }} onChange={citySelect} options={provinceData} defaultValue={''} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>机构介绍</span><Input.TextArea style={{ height: 80, }} ref={orgmsgRef} /></p>
      </Modal>
    </Content>
    
  )

}
